package com.ygqh.baby.service.impl;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import com.ygqh.baby.ao.*;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.mapper.YgFileTemplateMapper;
import com.ygqh.baby.po.YgFileTemplate;
import com.ygqh.baby.po.YgFileTemplateExample;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.YgFileTemplateService;

/**
 * @author admin
 */
@Service
public class YgFileTemplateServiceImpl implements YgFileTemplateService {

	@Autowired
	private YgFileTemplateMapper ygFileTemplateMapper;
	@Autowired
	private RedisDao redisDao;

	@Override
	public List<YgFileTemplate> find() {
		YgFileTemplateExample example = new YgFileTemplateExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return ygFileTemplateMapper.selectByExample(example);
	}

	@Override
	public int findCount() {
		YgFileTemplateExample example = new YgFileTemplateExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return ygFileTemplateMapper.countByExample(example);
	}

	@Override
	public YgFileTemplate findById(Long id) {
		return ygFileTemplateMapper.selectByPrimaryKey(id);
	}


	@Override
	public int save(YgFileTemplate ygFileTemplate) {
		return ygFileTemplateMapper.insertSelective(ygFileTemplate);
	}

	@Override
	public int update(YgFileTemplate ygFileTemplate) {
		return ygFileTemplateMapper.updateByPrimaryKeySelective(ygFileTemplate);
	}


	@Override
	public int deleteSoft(Long[] ids) {
		Assert.notEmpty(ids);
		YgFileTemplateExample example = new YgFileTemplateExample();
		example.createCriteria().andIdIn(Arrays.asList(ids));
		YgFileTemplate record = new YgFileTemplate();
		record.setStatus(DataStatus.Delete);

		return ygFileTemplateMapper.updateByExampleSelective(record, example);
	}

	@Override
	public int deleteSoft(Long id) {
		return this.deleteSoft(new Long[]{id});
	}

	@Override
	public int saveOrUpdate(YgFileTemplate ygFileTemplate) {
		int r;
		if (ygFileTemplate.getId() != null) {
			r = this.update(ygFileTemplate);
		} else {
			r = this.save(ygFileTemplate);
		}
		return r;
	}

	@Override
	public List<YgFileTemplate> find(FileType fileType) {
		YgFileTemplateExample example = new YgFileTemplateExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name()).andImgTypeEqualTo(fileType.name());
		example.setOrderByClause("area_name");
		return ygFileTemplateMapper.selectByExampleWithBLOBs(example);
	}

	@Override
	public int updateImageStatus(String name) {
		return ygFileTemplateMapper.updateImageStatus(name);


	}

	@Override
	public int insertFileByList(List<YgFileTemplate> list, String updateBy,
								Date updateTime) {
		return ygFileTemplateMapper.insertFileByList(list, updateBy, updateTime);

	}

	@Override
	public int updateImageStatusByAreaName(String name, String updateBy,
										   Date updateTime) {
		return ygFileTemplateMapper.updateImageStatusByAreaName(name, updateBy, updateTime);
	}

	@Override
	public String findCategoryImg(FileType fileType) {
		String key=String.format(RedisConstant.PAGE_TEMPLATE_PREFIX, fileType.name());
		String img = redisDao.get(key);
		if (StringUtils.isBlank(img)) {
			List<YgFileTemplate> templateList = this.find(fileType);
			if (!CollectionUtils.isEmpty(templateList)) {
				img = templateList.get(0).getImgPath();
				redisDao.set(key, img, 0);
			}
		}
		return img;
	}

	@Override
	public ResultSet<YgFileTemplate> searchMallStartList(QueryInfo queryInfo,String imgType) {
		int total = ygFileTemplateMapper.countBySmallStart(imgType);
		if (total <= 0) {
			return new ResultSet<>();
		}
		List<YgFileTemplate> result = ygFileTemplateMapper.selectListBySmallStart(queryInfo,imgType);
		return new ResultSet<>(total, result);
	}

	@Override
	public Message updateStartTimeAndStatus(Long id, Date startTime, DataStatus status, String handler) {
		YgFileTemplate fileTemplate = this.findById(id);
//		if (fileTemplate == null || !FileType.Mall.equals(fileTemplate.getImgType())) {
//			return Message.error("页面模板不存在", null);
//		}
		YgFileTemplate record = new YgFileTemplate();
		record.setId(id);
		record.setUpdateBy(handler);
		Date now = new Date();
		record.setUpdateTime(now);

		if (DataStatus.Delete.equals(status)) {
			if (status.equals(fileTemplate.getStatus())) {
				return Message.error("页面数据状态异常，请刷新页面重试", null);
			}
			if (fileTemplate.getStartTime() != null && now.after(fileTemplate.getStartTime())) {
				return Message.error("页面已生效，不可以禁用", null);
			}
			record.setStatus(DataStatus.Delete);
		} else if (startTime == null) {
			return Message.error("启用页面需要设置生效时间", null);
		} else if (ygFileTemplateMapper.existsValidMall(startTime,fileTemplate.getImgType().name())) {
			return Message.error("设置的时间将永不生效", null);
		} else {
			record.setStartTime(startTime);
			String redisKey=String.format(RedisConstant.MALL_TEMPLATE_KEY,fileTemplate.getImgType().name());
			redisDao.del(redisKey);
		}
		this.update(record);
		return Message.success(null);
	}

	@Override
	public String findValidMallImgPath(FileType fileType) {
		String redisKey=String.format(RedisConstant.MALL_TEMPLATE_KEY,fileType.name());
		String result = redisDao.get(redisKey);
		if (StringUtils.isBlank(result)) {
			List<YgFileTemplate> list = ygFileTemplateMapper.selectValidMall(fileType.name());
			if (CollectionUtils.isEmpty(list)) {
				return null;
			}
			list.sort(Comparator.comparing(YgFileTemplate::getStartTime));
			result = list.get(0).getImgPath();
			if (list.size() == 1) {
				redisDao.set(redisKey, result, 0);
			} else {
				redisDao.set(redisKey, result, list.get(1).getStartTime().getTime());
			}
		}
		return result;
	}

}

